import akshare as ak
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

df = ak.stock_zh_a_hist("603860", period= "daily", start_date="20240125" , end_date='20241203')


#数据预处理
#计算5日和20日移动平均线
df["MA5"] = df["收盘"].rolling(window=5).mean()
df["MA20"] = df["收盘"].rolling(window=20).mean()

#计算明天的收盘价（这是要预测的目标）
df['Target'] = df["收盘"].shift(-1)

#删除有空值的行
df = df.dropna()

features = ["开盘", "最高", "最低", "收盘", "成交量", "MA5", "MA20"]
X = df[features]
y = df['Target']

#构建预测模型

# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建并训练模型
model = LinearRegression()
model.fit(X_train, y_train)

# 预测并查看准确率
accuracy = model.score(X_test, y_test)
print(f'模型准确率: {accuracy: .2%}')

# 预测最新一天的股价
latest_prediction = model.predict([X.iloc[-1]])[0]
print(f"预测明天的股价：${latest_prediction:.2f}")

# 对测试集进行预测
test_predictions = model.predict(X_test)
# 画出实际值和预测值的对比图
plt.figure(figsize=(13, 6))
plt.rcParams['font.family'] = ['Microsoft YaHei']
plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False  #解决符号显示不正常

plt.plot(y_test.values[:50], label='实际价格')
plt.plot(test_predictions[:50], label ='预测价格')

plt.legend()
plt.title('股份预测对比')
plt.show()